package dsl

import viewbuilder.support.WebViewBuilderExecuter
import Post

class PostDsl {

    def save(post, params) {
        if(post) {
            post = postService.loadPost(params.id)
            post.properties = params
            postService.populateTags(post, params.tagsAsString)
            post.save()
            return post
        }
        return null
    }

    def valid(obj) {
        if(invalid(obj)) {
            return null
        }
        return obj
    }

    def invalid(obj) {
        if(obj.validate()) {
            return null
        }
        return obj
    }

    def sendUser(Post post, String action) {
        if(post) {
            flash.id = post.urlTitle
            redirect(action:action)
        }
    }

    def editView(post) {
        return postView(post, "edit")
    }

    def readView(post) {
        return postView(post, "view")
    }

    def postView(post, view) {
        if(post) {
            def model = [post:post,
                    tags:tags,
                    blogConfig:blogConfig]
            def executer = new WebViewBuilderExecuter(this.class.classLoader,
                    grailsApplication.config.viewComponents.location,
                    grailsApplication.config.viewComponents.packageLocation)

            def scriptLocation = getScriptLocation(grailsApplication, view)
            executer.execute(servletContext, scriptLocation, model, request, null)
            return [text:executer.writer.toString()]
        }
    }

    def and() {
        return this
    }

    def then() {
        return this
    }

    def after(result) {
        return result
    }

    def to(args) {
        return args
    }

    def given(obj) {
        return obj
    }

}